﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Windows.Resources;
using System.IO;
using System.Threading;
using JsonTest1.Network;
using Microsoft.Phone.Tasks;
using JsonTest1.Media;
using System.Windows.Threading;
using Microsoft.Xna.Framework;
using JsonTest1.Utils;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Shell;
using JsonTest1.NetEngine;
using JsonTest1.DatabaseFramwork;
using JasonPopupDemo.Data;
using JsonTest1.Configure;
using JsonTest1.UI;
using JsonTest1.CControl;
using JsonTest1.Net;
using JsonTest1.Data;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.Diagnostics;


namespace JsonTest1
{
    public partial class MainPage : PhoneApplicationPage,IHttpStateListener
    {
        bool fromMyTile = false;
        private MyViewModel _ViewModel;

       // private CState cState ;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            //cState = new CState(this);

            _ViewModel = MyViewModel.GetInstance();
            MyTable table = new MyTable();
            table.Name = "123";
           // MyViewModel.GetInstance().SaveData(table);

            MyViewModel.GetInstance().SelectData();

            //Json 访问
           /* StreamResourceInfo reader = Application.GetResourceStream(new Uri("/JsonTest1;component/Res/json.txt", UriKind.Relative));
            StreamReader stringReader = new StreamReader(reader.Stream);
            JObject json = JObject.Parse(stringReader.ReadToEnd());
            WeatherData weatherData = new WeatherData
            {
                city = (string)json["weatherinfo"]["city"],
                cityid = (string)json["weatherinfo"]["cityid"],
                isRader = (string)json["weatherinfo"]["isRader"],
                Rader = (string)json["weatherinfo"]["Rader"],
                SD = (string)json["weatherinfo"]["SD"],
                temp = (string)json["weatherinfo"]["temp"],
                time = (string)json["weatherinfo"]["time"],
                WD = (string)json["weatherinfo"]["WD"],
                WS = (string)json["weatherinfo"]["WS"],
                WSE = (string)json["weatherinfo"]["WSE"]
            };*/

            // MessageBox.Show(weatherData.city);

           // new Thread(startNetwrok).Start();


            this.c_listbox.MainItemListBox.SelectionChanged += new SelectionChangedEventHandler(listBox1_SelectedIndexChanged);

            string[] sources = new string[]
            {
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526395.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526396.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526397.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526398.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526399.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526400.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526401.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526402.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526403.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526404.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526405.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526406.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526407.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526408.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526409.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526410.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526411.jpg",
                "http://gb.cri.cn/mmsource/images/2008/05/26/ei080526412.jpg"
            };
            foreach(string source in sources)
            {
                FileTaskpool.Instance().AddTask(source, this); 
            }

            
        }

        
      /*  private class CState : IHttpStateListener
        {
            MainPage page;
            public CState(MainPage page)
            {
                this.page = page;
            }

            
        }*/

        public void HttpFailCalback(int failType, int errorType, ResultData data) { }
        public void HttpDataStreamCalback(Stream stream, ResultData data)
        {
            // BitmapSource bs = new BitmapImage();
            //  bs.SetSource(stream);

            //写入数据
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            string dir = "Images";//保存图片的目录
            if (!myIsolatedStorage.DirectoryExists(dir))//判断目录是否存在
                myIsolatedStorage.CreateDirectory(dir);//创建目录
            //imageSavePath = dir + "\\" + zimgName;//拼接图片保存路径
            if (!myIsolatedStorage.FileExists(dir))
            {


                using (Stream storageFileStream = myIsolatedStorage.OpenFile(dir + "\\" + MD5.GetMd5String(data.RData.ToString()), FileMode.Create, FileAccess.Write))
                {
                    #region 保存jpg格式的图片
                    //BitmapImage image = new BitmapImage();
                    //image.SetSource(stream);
                    //WriteableBitmap wb = new WriteableBitmap(image);
                    //System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, storageFileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                    ////另一种保存图片的方法
                    ////wb.SaveJpeg(storageFileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                    ////以下的方法是用来读取程应用程序包中的图片
                    ////StreamResourceInfo resourceInfo = Application.GetResourceStream(new Uri(picPath));
                    ////BitmapImage bitmap = new BitmapImage();
                    ////bitmap.SetSource(resourceInfo.Stream);
                    #endregion
                    #region 保存png格式的图片
                    byte[] _imgBytes = new byte[stream.Length];
                    stream.Read(_imgBytes, 0, _imgBytes.Length);
                    storageFileStream.Write(_imgBytes, 0, _imgBytes.Length);

                    #endregion
                }
            }
            Debug.WriteLine(Thread.CurrentThread.ToString() + data.RData.ToString());

            /* Thread.Sleep(5*1000);
             page.Dispatcher.BeginInvoke(() =>
             {
                 BitmapSource bs = new BitmapImage();
                 bs.SetSource(stream);
                 page.img.Source = bs;
             });*/
            BitmapSource bs = new BitmapImage();
            bs.SetSource(stream);
            img.Source = bs;



        }
        public void HttpProgressChangedCalback(int progress, long totalProgress, HTTP_TYPE type) { }
        public void HttpCompleted() { }


        public void startNetwrok()
        {
            Call.Download(this);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault(n=>n.NavigationUri.ToString().Contains("s=1"));
            if (tile != null)
            {
                fromMyTile = true;
            }
            else {
                fromMyTile = false;
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {


            if (1 == 1)
            {
               
                return;
            }
            ShellTile title = ShellTile.ActiveTiles.FirstOrDefault(m => m.NavigationUri.ToString().Contains("s=1"));
            if (title != null)
            {
                StandardTileData data = new StandardTileData();
                data.Title = "new -1";
                data.Count = 3;
                data.BackTitle = "back-1";
                data.BackContent = "back-content";
                title.Update(data);
                MessageBox.Show("磁贴数据更新完成.");
            }
            else {
                // 创建新磁贴   
                int Counter = 0;
                StandardTileData data = new StandardTileData()
                {
                    Title = "1----",
                    Count = 2,
                    BackContent = "back---content",
                    BackgroundImage = new Uri("Background.png", UriKind.Relative),
                    BackBackgroundImage = new Uri("Background.png", UriKind.Relative)
                };
                ShellTile.Create(new Uri("/MainPage.xaml?s=1", UriKind.Relative), data);
                MessageBox.Show("磁贴图块创建成功。");   
            }

            /*WebBrowserTask webBrowser = new WebBrowserTask();
            webBrowser.URL = "http://www.baidu.com";
            webBrowser.Show();*/

            /*SearchTask searchTask = new SearchTask();
            searchTask.SearchQuery = "window phone7";
            searchTask.Show();*/

            // new AudioPlayerEngine().start(new Uri("/Res/Audio/test_cbr.mp3",UriKind.Relative));
           /* FileUtil.CopyToIsolatedStorage(new string[] { "/JsonTest1;component/Res/Audio/test_cbr.mp3" });

            BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri("test_cbr.mp3", UriKind.Relative), "Ring01", "少女时代", "the boys the 3rd album", null);
            BackgroundAudioPlayer.Instance.Play();*/
           
            //new AudioPlayer().PlayTrack(new Uri("/Res/Audio/test_cbr.mp3", UriKind.Relative));

        }

        /*
        处理点击事件
        */
        public void listBox1_SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
        {
            MainItem mainItem = (MainItem)this.c_listbox.MainItemListBox.SelectedValue;
            var root = App.Current.RootVisual as PhoneApplicationFrame;
            switch (mainItem.Type)
            {
                case Constants.TYPE_SEARCH:
                    {
                        
                        SearchPage.NavPage(this, mainItem);
                    }
                    break;
                case Constants.TYPE_RADIO:
                    {
                        CProgressDialog progress = new CProgressDialog(this);
                        progress.Show();
                        
                    }
                    break;
            }
        }


        private void button2_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Pivot/PivotMain.xaml",UriKind.Relative));
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Pivot/PanoramaMain.xaml", UriKind.Relative));
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Pivot/SpinnerMain.xaml", UriKind.Relative));
        }

        private void button3_Click_1(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Pivot/SpinnerMain.xaml", UriKind.Relative));
        }

    }
}